﻿using System;
using System.IO;
using System.Threading;
using System.Web.UI;
using System.Xml;
using visinia.SmartEngine;
using visinia.SmartEngine.Installer;
using visinia.SmartEngine.Modules;

namespace visinia.web.admin.pages
{
    public partial class ModuleSettingsPage : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if ((Thread.CurrentPrincipal.IsInRole("designer") || (Thread.CurrentPrincipal.IsInRole("admin"))))
            {
                if (Request.QueryString["ModuleId"] == null)
                    return;
                ModuleInfo info = ModuleController.GetModule(Convert.ToInt32(Request.QueryString["ModuleId"]));
                if (info == null)
                    return;
                MODULE_ID.Value = info.ModuleId.ToString();
                MODULE_TITLE.Value = info.Title;
                MODULE_TITLE_IMAGE_URL.Value = info.TitleImageUrl;
                MODULE_TITLE_IMAGE_NAVIGATION_URL.Value = info.TitleImageNavigationUrl;
                MODULE_WIDTH.Value = info.Width.ToString();
                MODULE_HEIGHT.Value = info.Height.ToString();
                MODULE_CSSCLASS.Value = info.CssClass;
                MODULE_VISIBLE.SelectedValue = info.Visible.ToString();
                // will be shown as the settings dialog title
                ModuleInstalled installedModule = ModulesInstalledController.GetInstalledModule(info.ModuleInstalledId);
                MODULE_NAME.Value = installedModule.Name;
                LoadModuleHelp(installedModule.Help);
                if (!string.IsNullOrEmpty(info.ModuleSettingsUrl))
                {
                    MODULE_PRIVATE_SETTINGS.Visible = true;
                    WebSettingsModule SettingControl = (WebSettingsModule)LoadControl(WebRoots.GetModulesRoot + info.ModuleSettingsUrl);
                    SettingControl.ModuleId = info.ModuleId;
                    MODULE_PRIVATE_SETTINGS.Controls.Add(SettingControl);
                }
            }
        }

        private void LoadModuleHelp(string HelpFile)
        {
            string helpFile = Server.MapPath(WebRoots.GetModulesRoot + HelpFile);
            if (File.Exists(helpFile))
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(helpFile);
                XmlNode root = doc["help"];
                if (root != null)
                    CONTENTS.Controls.Add(new LiteralControl(root.InnerXml));
            }
        }
    }
}